//
//  CustomDateView.m
//  SmartWatch
//
//  Created by zwj on 2022/11/29.
//

@interface CalendarDayItem : NSObject
@property (nonatomic,strong)NSDate *date;
@property (nonatomic,assign)BOOL isOtherMonth;
@property (nonatomic,assign)BOOL isSelected;
@property (nonatomic,strong)UIColor *eventDotColor;
@property (nonatomic,assign)BOOL showEventDot;
@property(nonatomic,copy) NSString *statusStr;// 每一时间的值
@end

@implementation CalendarDayItem

- (void)setStatusStr:(NSString *)statusStr {
    _statusStr = statusStr;
}

@end

@interface CalendarCollectionCell : UICollectionViewCell
@property (nonatomic,strong)CalendarDayItem *item;
@property(nonatomic,strong) UIImageView *painuanRiImage;
@property(nonatomic,strong) UILabel *textLabel;
@property(nonatomic,strong) UIView *backView;

@end

@implementation CalendarCollectionCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(4, 4, self.width - 8, self.height - 8)];
        ViewBorder(backView, 1, COLOR_0);
        backView.backgroundColor = COLOR_4;
        [self.contentView  addSubview:backView];
        self.backView = backView;
        
        UILabel *textLabel = [UILabel createLabelText:@"10" font:UIFontMake(14) textColor:COLOR_0];
        textLabel.frame = backView.bounds;
        textLabel.textAlignment = NSTextAlignmentCenter;
        [backView addSubview:textLabel];
        self.textLabel = textLabel;
        
        UIImageView *painuanRiImage = [[UIImageView alloc]initWithFrame:CGRectMake((backView.width - 12)/2.0, 3, 12, 12)];
        painuanRiImage.image = UIImageMake(@"watch_painuanri");
        [backView  addSubview:painuanRiImage];
        painuanRiImage.hidden = YES;
        self.painuanRiImage = painuanRiImage;
    }
    return self;
}

- (void)setItem:(CalendarDayItem *)item{
    _item = item;
    
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.timeZone = [self calendar].timeZone;
        [dateFormatter setDateFormat:@"dd"];
    }
    
    self.textLabel.text = [dateFormatter stringFromDate:item.date];
    if(item.isOtherMonth){
        self.textLabel.textColor = COLOR999;
        ViewBorder(self.backView, 1, COLOR999);
        self.backView.backgroundColor = COLOR_4;
        self.painuanRiImage.hidden = YES;
    }else{
        if (item.isSelected) {
            self.textLabel.textColor = UIColorRed;
            self.backView.backgroundColor = COLOR_4;
            ViewBorder(self.backView, 1, UIColorRed);
            self.painuanRiImage.hidden = YES;
        }else{
            // 1 月经期 2 ，4 安全期  3排卵期 100 排卵日
            if([item.statusStr isEqualToString:@"1"]){
                self.textLabel.textColor = COLOR_4;
                self.backView.backgroundColor = HexColor(@"#FF6694");
                ViewBorder(self.backView, 0.5, HexColor(@"#E3E3E3"));
                self.painuanRiImage.hidden = YES;
            }else if ([item.statusStr isEqualToString:@"2"] || [item.statusStr isEqualToString:@"4"]){
                self.textLabel.textColor = HexColor(@"#29B52E");
                self.backView.backgroundColor = HexColor(@"#ECFCED");
                ViewBorder(self.backView, 0.5, HexColor(@"#E3E3E3"));
                self.painuanRiImage.hidden = YES;
            }else if ([item.statusStr isEqualToString:@"3"]){
                self.textLabel.textColor = HexColor(@"#B85FFF");
                self.backView.backgroundColor = HexColor(@"#FAF4FF");
                ViewBorder(self.backView, 0.5, HexColor(@"#E3E3E3"));
                self.painuanRiImage.hidden = YES;
            }else if ([item.statusStr isEqualToString:@"100"]){
                self.textLabel.textColor = HexColor(@"#B85FFF");
                self.backView.backgroundColor = HexColor(@"#FAF4FF");
                ViewBorder(self.backView, 0.5, HexColor(@"#E3E3E3"));
                
                self.painuanRiImage.hidden = NO;
            }
        }
        
    }
    
    
}

- (NSCalendar *)calendar
{
    static NSCalendar *calendar;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
#ifdef __IPHONE_8_0
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
#else
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
#endif
        calendar.timeZone = [NSTimeZone localTimeZone];
    });
    
    return calendar;
}


@end

#import "CustomDateView.h"
#import "CalendarCollectionViewFlowLayout.h"
#define NUMBER_PAGES_LOADED 12
#define WeeksToDisplay      6
#define BeforeMonth         2

@interface CustomDateView ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    //是否是在点击日期或者滑动改变页数
    BOOL isOwnChangePage;
}
@property(nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong)NSDate *currentDate;
@property (nonatomic,strong)NSArray *daysInMonth;
@property (nonatomic,assign)NSInteger currentMonthIndex;
@property (nonatomic,strong)NSIndexPath *currentSelectedIndexPath;
@property(nonatomic,strong) UILabel *content;


@end


@implementation CustomDateView

- (instancetype)initWithFrame:(CGRect)frame periodLength:(NSInteger)periodLength menstrualPeriod:(NSInteger)menstrualPeriod periodStartTime:(NSString *)periodStartTime
{
    self = [super initWithFrame:frame];
    if (self) {
        
        MyLinearLayout *root = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
        root.myHorzMargin = 0;
        root.myHeight = frame.size.height;
        [self addSubview:root];
        
        MyLinearLayout *yueLay = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        yueLay.myHorzMargin = 0;
        yueLay.gravity = MyGravity_Center;
        yueLay.myHeight = 20;
        yueLay.subviewHSpace = 20;
        [root addSubview:yueLay];
        
        
        for (int i = 0; i < 2; i++) {
            UIImageView *right = [[UIImageView alloc]initWithImage:UIImageMake(i==0?@"date_left":@"date_right")];
            right.mySize = CGSizeMake(20, 20);
            right.userInteractionEnabled = YES;
            right.tag = 100 + i;
            [yueLay addSubview:right];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftRightClick:)];
            [right addGestureRecognizer:tap];
            
            if(i==0){
                UILabel *content = [UILabel createLabelText:@"" font:UIFontMake(15) textColor:COLOR1515];
                content.mySize = kAutoSize;
                [yueLay addSubview:content];
                self.content = content;
            }
        }
        
        MyLinearLayout *zhouLay = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        zhouLay.myHorzMargin = 0;
        zhouLay.gravity = MyGravity_Vert_Center | MyGravity_Horz_Around;
        zhouLay.myHeight = 20;
        zhouLay.myTop = 20;
        [root addSubview:zhouLay];
        
        NSArray *zhouArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
        for (int i = 0; i < zhouArray.count; i++) {
            UILabel *content = [UILabel createLabelText:zhouArray[i] font:UIFontMake(13) textColor:HexColor(@"#454545")];
            content.mySize = kAutoSize;
            [zhouLay addSubview:content];
        }
        
        CGFloat itemWidth = (self.width )/7.0;
        CGFloat itemHeight = (self.height - 60 - 12)/WeeksToDisplay;
        CalendarCollectionViewFlowLayout *layout = [CalendarCollectionViewFlowLayout new];
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        layout.itemCountPerRow = 7;
        layout.rowCount = WeeksToDisplay;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.weight = 1;
        collectionView.myTop = 12;
        collectionView.myHorzMargin = 0;
//        collectionView.backgroundColor = THEME_COLOR;
        [collectionView registerClass:[CalendarCollectionCell class] forCellWithReuseIdentifier:@"dayCell"];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.pagingEnabled = YES;
        collectionView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [root addSubview:collectionView];
        self.collectionView = collectionView;
        
        
        
        [self getDateDatasperiodLength:periodLength menstrualPeriod:menstrualPeriod periodStartTime:periodStartTime];
        
        
    }
    return self;
}

- (void)leftRightClick:(UITapGestureRecognizer *)tap {
    
    CGFloat pageWidth = CGRectGetWidth(self.frame);
    CGFloat fractionalPage = self.collectionView.contentOffset.x / pageWidth;
    
    int currentPage = roundf(fractionalPage);
    
    if(currentPage == 0 && tap.view.tag == 100){
        return;
    }
    if(currentPage == NUMBER_PAGES_LOADED - 1 && tap.view.tag == 101){
        return;
    }
    
    if(tap.view.tag == 100){
        currentPage--;
    }else{
        currentPage++;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.collectionView setContentOffset:CGPointMake(currentPage * pageWidth, 0)];
    }];
    
    CalendarDayItem *item = self.daysInMonth[currentPage][15];
    _content.text = [self updateTopYearMonth:item.date];
}

- (NSString *)updateTopYearMonth:(NSDate *)date {
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    format.dateFormat = @"yyyy-MM";
    NSString * dateStr = [format stringFromDate:date];
    return dateStr;
}

#pragma mark -- UICollectionViewDataSource --
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return NUMBER_PAGES_LOADED;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7*WeeksToDisplay;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CalendarCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dayCell" forIndexPath:indexPath];
    CalendarDayItem *item = self.daysInMonth[indexPath.section][indexPath.row];
    cell.item = item;
    return cell;
}

#pragma mark -- UICollectionViewDelegate --
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CalendarDayItem *item = self.daysInMonth[indexPath.section][indexPath.row];
    if(!item.isOtherMonth){
        !self.selectDateClick?:self.selectDateClick(item.statusStr.integerValue);
    }
}

#pragma mark -- UIScrollView --

//手指滑动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //如果是按周显示
    CGFloat pageWidth = CGRectGetWidth(self.frame);
    CGFloat fractionalPage = self.collectionView.contentOffset.x / pageWidth;
    
    int currentPage = roundf(fractionalPage);
    
    CalendarDayItem *item = self.daysInMonth[currentPage][15];
    _content.text = [self updateTopYearMonth:item.date];
}

- (void)getDateDatasperiodLength:(NSInteger)periodLength menstrualPeriod:(NSInteger)menstrualPeriod periodStartTime:(NSString *)periodStartTime {
    NSCalendar *calendar = [self calendar];
    
    if (self.currentDate == nil) {
        self.currentDate = [NSDate date];
    }
    
    int index = 0;
    // 月经期 4，5，6，7，8
    // 周期   24  ~ 35
    
    NSInteger secAnQuan = 9;
    
    NSInteger painuanqi = 0;
    NSInteger firstAnQuan = 0;
    
    
    
    

    if(periodLength - secAnQuan - menstrualPeriod < 10){
        firstAnQuan = 0;
        painuanqi = periodLength - menstrualPeriod - secAnQuan;
    }else{
        painuanqi = 10;
        firstAnQuan = periodLength - painuanqi - secAnQuan - menstrualPeriod;
    }
    
    
    
    NSLog(@" menstrualPeriod = %ld firstAnQuan = %ld painuanqi = %ld  secAnQuan = %ld",menstrualPeriod,firstAnQuan, painuanqi,secAnQuan);
    
    // 把整个月经期时间整理成数组，以便于放在下面做循环
    NSMutableArray *zhouqiArray = @[].mutableCopy;
    
    for (int i = 0; i < menstrualPeriod; i++) {
        [zhouqiArray addObject:@"1"];
    }
    for (int i = 0; i < firstAnQuan; i++) {
        [zhouqiArray addObject:@"2"];
    }
    for (int i = 0; i < painuanqi; i++) {
        // 6 第6天为排卵日
        if(i == 5){
            [zhouqiArray addObject:@"100"];
        }else{
            [zhouqiArray addObject:@"3"];
        }
    }
    for (int i = 0; i < secAnQuan; i++) {
        [zhouqiArray addObject:@"4"];
    }
    NSLog(@"zhouqiArray   %@  zhouqiArray.count %ld",zhouqiArray,zhouqiArray.count);
    NSInteger zhouqiTag = 0;
    
    NSMutableArray *daysInMonths = [@[] mutableCopy];
    for(int a = 0; a < NUMBER_PAGES_LOADED; a++){

        NSDateComponents *dayComponent = [NSDateComponents new];


        dayComponent.month = a - BeforeMonth;
        //当前日期后面10个月
        NSDate *monthDate = [calendar dateByAddingComponents:dayComponent toDate:self.currentDate options:0];

        if(a == 0){
            _content.text  = [ self updateTopYearMonth:monthDate];
        }
        
        monthDate = [self beginningOfMonth:monthDate];

        
        
        {
            NSDate *singleDate = monthDate;

            //每一月的 date
            NSMutableArray *daysOfMonth = [@[] mutableCopy];
            {
                NSDateComponents *comps = [calendar components:NSCalendarUnitMonth|NSCalendarUnitDay fromDate:singleDate];

                self.currentMonthIndex = comps.month;

                //每月开始的第一天不是 1   则是上一个月的
                if(comps.day > 1){
                    self.currentMonthIndex = (self.currentMonthIndex % 12) + 1;

                }
            }

            for (NSInteger i = 0; i< WeeksToDisplay; i++) {
                NSDateComponents *dayComponent = [NSDateComponents new];
                dayComponent.day = 7;

                {
                    NSDate *weekDate = singleDate;

                    
                    //每一周的 date
                    NSMutableArray *daysOfweek = [@[] mutableCopy];

                    for (NSInteger c=0; c<7; c++) {
                        NSDateComponents *comps = [calendar components:NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth fromDate:weekDate];
                        NSInteger monthIndex = comps.month;

                        CalendarDayItem *item = [CalendarDayItem new];
                        item.isOtherMonth = monthIndex != self.currentMonthIndex;
                        item.date = weekDate;
                        if ([self isEqual:weekDate other:self.currentDate]) {
                            item.isSelected = YES;
                            self.currentSelectedIndexPath = [NSIndexPath indexPathForItem:(comps.weekOfMonth-1)*7+c inSection:round(NUMBER_PAGES_LOADED / 2)];

                        }
                        


                        if(!item.isOtherMonth){

                            NSInteger days;
                            NSUInteger shengyu = 0;
                            // 找到第一个日期日期是属于月经期的哪一天
                            if(index == 0){
                                // 首选获取选择的日期和第一天相差多少天，再算出余多少天，最后算出从周期数组的第几个开始取值
                                days =  [self getDifferenceByDate:periodStartTime withFirstDate:weekDate];
                                NSLog(@"days  %ld",days);
                                shengyu = labs(days % periodLength);
                                NSLog(@"shengyu  %ld",shengyu);
                                zhouqiTag = zhouqiArray.count - shengyu;
                                NSLog(@"zhouqiTag  %ld",zhouqiTag);
                                
                            }
                            
                            if(zhouqiTag == zhouqiArray.count){
                                zhouqiTag = 0;
                            }
                            
                            item.statusStr = zhouqiArray[zhouqiTag];
                            
                            zhouqiTag++;
                            index++;
                        }
                        
                        

                        NSDateComponents *dayComponent = [NSDateComponents new];
                        dayComponent.day = 1;
                        weekDate = [calendar dateByAddingComponents:dayComponent toDate:weekDate options:0];
                        
                        [daysOfweek addObject:item];


                    }

                    [daysOfMonth addObjectsFromArray:daysOfweek];
                }



                singleDate = [calendar dateByAddingComponents:dayComponent toDate:singleDate options:0];
            }

            [daysInMonths addObject:daysOfMonth];
        }



    }
    
    self.daysInMonth = daysInMonths;
    [self.collectionView reloadData];
    
    
}

- (NSDate *)getNewCurrentDate{
    CGFloat pageWidth = CGRectGetWidth(self.frame);
    CGFloat fractionalPage = self.collectionView.contentOffset.x / pageWidth;
    
    int currentPage = roundf(fractionalPage);
    
    NSCalendar *calendar = [self calendar];
    NSDateComponents *dayComponent = [NSDateComponents new];
    NSDate *currentDate;
    dayComponent.day = 0;
    dayComponent.month = currentPage - (NUMBER_PAGES_LOADED / 2);
    currentDate = [calendar dateByAddingComponents:dayComponent toDate:self.currentDate options:0];
  
    return currentDate;
}

- (NSCalendar *)calendar
{
    static NSCalendar *calendar;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
#ifdef __IPHONE_8_0
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
#else
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
#endif
        calendar.timeZone = [NSTimeZone localTimeZone];
    });
    
    return calendar;
}

/**
 *  返回该日期月数第一周开始的第一天
 *
 *  @param date  date
 *
 *  @return date
 */
- (NSDate *)beginningOfMonth:(NSDate *)date{
    NSCalendar *calendar = [self calendar];
    
    NSDateComponents *componentsCurrentDate =[calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfMonth fromDate:date];
    
    
    NSDateComponents *componentsNewDate = [NSDateComponents new];
    
    componentsNewDate.year = componentsCurrentDate.year;
    componentsNewDate.month = componentsCurrentDate.month;
    componentsNewDate.weekOfMonth = 1;
    componentsNewDate.weekday = calendar.firstWeekday;
    
    return [calendar dateFromComponents:componentsNewDate];
    
}

- (NSInteger)getDifferenceByDate:(NSString *)date withFirstDate:(NSDate *)firstDate{
       
        //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *oldDate = [dateFormatter dateFromString:date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:oldDate  toDate:firstDate  options:0];
    return [comps day];
}



///比较日期是否相等
- (BOOL)isEqual:(NSDate *)date1 other:(NSDate *)date2{
    
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.timeZone = [self calendar].timeZone;
    dateFormatter.dateFormat = @"yyyy.MM.dd";
    
    return [[dateFormatter stringFromDate:date1] isEqualToString:[dateFormatter stringFromDate:date2]];
    
}
@end



